package com.bc004346.travelus.fragment;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bc004346.travelus.R;
import com.bc004346.travelus.dataAccess.SQLHelper;
import com.bc004346.travelus.dataAccess.TravelUsScreenScraper;
import com.bc004346.travelus.model.TravelUsException;
import com.bc004346.travelus.model.domain.Flight;
import com.bc004346.travelus.utility.Utility;

import static com.bc004346.travelus.utility.Utility.log;

/**
 * Created by Renats on 11/20/2014.
 * Checkin presentation layer
 */
public class CheckinFragment extends Fragment {

    //<editor-fold desc="Members">
    private SQLHelper mSqlHelper;
    public static final String FLIGHT_EXTRA = "com.bc004346.travelus.fragment.CheckinFragment.FLIGHT";
    private Flight mFlight;
    private EditText mBadge;
    private EditText mPNR;
    private EditText mOrigin;
    private TextView mMessage;
    private FrameLayout mProgressBar;
    //</editor-fold>

    public SQLHelper getSqlHelper() {
        if (mSqlHelper == null) {
            mSqlHelper = new SQLHelper(getActivity().getApplicationContext());
        }
        return mSqlHelper;
    }

    public static CheckinFragment newInstance(Flight flight) {
        Bundle args = new Bundle();
        args.putSerializable(FLIGHT_EXTRA, flight);
        CheckinFragment fragment = new CheckinFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //<editor-fold desc="Overrides">
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            mFlight = (Flight) getArguments().getSerializable(FLIGHT_EXTRA);
            log(mFlight.toString());
        } catch (Exception ex) {
            log(ex);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        try {
            outState.putSerializable(FLIGHT_EXTRA, mFlight);
        } catch (Exception e) {
            Utility.log(e.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        @SuppressLint("InflateParams")
        View v = inflater.inflate(R.layout.fragment_checkin, null);
        try {
            mBadge = (EditText) v.findViewById(R.id.fragment_checkin_badge);
            mPNR = (EditText) v.findViewById(R.id.fragment_checkin_pnr);
            mOrigin = (EditText) v.findViewById(R.id.fragment_checkin_origin);
            mMessage = (TextView) v.findViewById(R.id.fragment_checkin_message);
            mProgressBar = (FrameLayout) v.findViewById(R.id.fragment_checkin_progressBar_container);
            Button buttonCheckin = (Button) v.findViewById(R.id.fragment_checkin_button_checkin);
            Button buttonIgnore = (Button) v.findViewById(R.id.fragment_checkin_button_ignore);

            mProgressBar.setVisibility(View.INVISIBLE);
            mBadge.setText(Utility.username);
            if (mFlight != null) {
                mPNR.setText(mFlight.getPnr());
                mOrigin.setText(mFlight.getOrigin());
            }
            else
                buttonIgnore.setVisibility(View.INVISIBLE);

            buttonCheckin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(validFields())doCheckin();
                }

            });

            buttonIgnore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mFlight.setIsCheckedIn(true);
                    getSqlHelper().UpdateFlight(mFlight);
                    log("Flight " + mFlight.toString() + " has been updated as checked in = " + mFlight.isCheckedIn());
                    getActivity().finish();
                }
            });

        } catch (Exception ex) {
            log(ex);
        }
        return v;
    }

    private boolean validFields() {

        if(mBadge == null || mBadge.getText() == null || mBadge.getText().toString().length() < 5) {
            mMessage.setText("Invalid badge / login.");
            return false;
        }

        if(mPNR == null || mPNR.getText() == null || mPNR.getText().toString().length() != 6) {
            mMessage.setText("Invalid PNR");
            return false;
        }

        if(mOrigin == null || mOrigin.getText() == null || mOrigin.getText().toString().length() != 3) {
            mMessage.setText("Invalid Origin. Please supply 3-char airport code");
            return false;
        }

        return true;
    }

    private void doCheckin() {
        mProgressBar.setVisibility(View.VISIBLE);
        mMessage.setText("");
        new AsyncTask<Void, Void, Boolean>() {

            private Exception ex;

            @Override
            protected Boolean doInBackground(Void... flights) {
                Boolean result = false;
                try {
                    TravelUsScreenScraper dao = Utility.getInstance().getBackgroundTravelUS();
                    result = dao.doCheckin(
                            mBadge.getText().toString(),
                            mPNR.getText().toString(),
                            mOrigin.getText().toString());
                } catch (TravelUsException e) {
                    ex = e;
                }

                return result;
            }

            @Override
            protected void onPostExecute(Boolean success) {
                String x;

                if (ex != null) x = "Unable to checkin: " + ex.getMessage();
                else if (mFlight != null && !success) x = "Unable to checkin for flight " + mFlight.toString();
                else if (mFlight == null && !success) x = "Unable to checkin for PNR " + mPNR.getText().toString().toUpperCase();
                else x = "You are checked in for your flight " + (mFlight == null ? "" : mFlight.toString());

                if(mFlight != null && success){
                    mFlight.setIsCheckedIn(true);
                    getSqlHelper().UpdateFlight(mFlight);
                }

                mMessage.setText(x);
                Toast.makeText(getActivity(), x, Toast.LENGTH_LONG).show();
                mProgressBar.setVisibility(View.INVISIBLE);
                if(success) getActivity().finish();
            }
        }.execute();
    }
    //</editor-fold>

}
